package com.liuguang.framework.utils;

import android.annotation.SuppressLint;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Environment;
import android.util.Log;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Map;
import java.util.Queue;
import java.util.Set;

public final class ImageUtil {
    private static final LinkedList<String> CACHE_ENTRIES = new LinkedList<>();
    private static int CACHE_SIZE = 20;
    private static final Map<String, Bitmap> IMG_CACHE_INDEX = new HashMap();
    private static final byte[] LOCKED = new byte[0];
    private static final Options OPTIONS_DECODE = new Options();
    private static final Options OPTIONS_GET_SIZE = new Options();
    private static String TAG = "ImageUtil";
    /* access modifiers changed from: private */
    public static final Queue<QueueEntry> TASK_QUEUE = new LinkedList();
    /* access modifiers changed from: private */
    public static final Set<String> TASK_QUEUE_INDEX = new HashSet();
    private static final int THUMB_SIZE = 100;
    private static final Size ZERO_SIZE = new Size(0, 0);

    static class QueueEntry {
        public int height;
        public String path;
        public int width;

        QueueEntry() {
        }
    }

    static class Size {
        private int height;
        private int width;

        Size(int i, int i2) {
            this.width = i;
            this.height = i2;
        }

        public int getWidth() {
            return this.width;
        }

        public int getHeight() {
            return this.height;
        }
    }

    static {
        OPTIONS_GET_SIZE.inJustDecodeBounds = true;
        new Thread() {
            {
                setDaemon(true);
            }

            public void run() {
                while (true) {
                    synchronized (ImageUtil.TASK_QUEUE) {
                        if (ImageUtil.TASK_QUEUE.isEmpty()) {
                            try {
                                ImageUtil.TASK_QUEUE.wait();
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                    QueueEntry queueEntry = (QueueEntry) ImageUtil.TASK_QUEUE.poll();
                    ImageUtil.TASK_QUEUE_INDEX.remove(ImageUtil.createKey(queueEntry.path, queueEntry.width, queueEntry.height));
                    ImageUtil.createBitmap(queueEntry.path, queueEntry.width, queueEntry.height);
                }
            }
        }.start();
    }

    public static Bitmap getBitmap(String str, int i, int i2) {
        if (str == null) {
            return null;
        }
        try {
            if (CACHE_ENTRIES.size() >= CACHE_SIZE) {
                destoryLast();
            }
            Bitmap useBitmap = useBitmap(str, i, i2);
            if (useBitmap != null && !useBitmap.isRecycled()) {
                return useBitmap;
            }
            Bitmap createBitmap2 = createBitmap2(str, i, i2);
            String createKey = createKey(str, i, i2);
            synchronized (LOCKED) {
                IMG_CACHE_INDEX.put(createKey, createBitmap2);
                CACHE_ENTRIES.addFirst(createKey);
            }
            return createBitmap2;
        } catch (OutOfMemoryError unused) {
            destoryLast();
            return createBitmap2(str, i, i2);
        }
    }

    /* JADX WARNING: Can't wrap try/catch for region: R(6:11|10|14|15|16|17) */
    /* JADX WARNING: Code restructure failed: missing block: B:12:0x002b, code lost:
        r0 = move-exception;
     */
    /* JADX WARNING: Code restructure failed: missing block: B:13:0x002c, code lost:
        r1 = r3;
        r3 = r0;
     */
    /* JADX WARNING: Failed to process nested try/catch */
    /* JADX WARNING: Missing exception handler attribute for start block: B:14:0x002f */
    /* Code decompiled incorrectly, please refer to instructions dump. */
    public static com.liuguang.framework.utils.ImageUtil.Size getBitMapSize(java.lang.String r3) {
        /*
            java.io.File r0 = new java.io.File
            r0.<init>(r3)
            boolean r3 = r0.exists()
            if (r3 == 0) goto L_0x0039
            r3 = 0
            java.io.FileInputStream r1 = new java.io.FileInputStream     // Catch:{ FileNotFoundException -> 0x002f }
            r1.<init>(r0)     // Catch:{ FileNotFoundException -> 0x002f }
            android.graphics.BitmapFactory$Options r0 = OPTIONS_GET_SIZE     // Catch:{ FileNotFoundException -> 0x0029, all -> 0x0027 }
            android.graphics.BitmapFactory.decodeStream(r1, r3, r0)     // Catch:{ FileNotFoundException -> 0x0029, all -> 0x0027 }
            com.liuguang.framework.utils.ImageUtil$Size r3 = new com.liuguang.framework.utils.ImageUtil$Size     // Catch:{ FileNotFoundException -> 0x0029, all -> 0x0027 }
            android.graphics.BitmapFactory$Options r0 = OPTIONS_GET_SIZE     // Catch:{ FileNotFoundException -> 0x0029, all -> 0x0027 }
            int r0 = r0.outWidth     // Catch:{ FileNotFoundException -> 0x0029, all -> 0x0027 }
            android.graphics.BitmapFactory$Options r2 = OPTIONS_GET_SIZE     // Catch:{ FileNotFoundException -> 0x0029, all -> 0x0027 }
            int r2 = r2.outHeight     // Catch:{ FileNotFoundException -> 0x0029, all -> 0x0027 }
            r3.<init>(r0, r2)     // Catch:{ FileNotFoundException -> 0x0029, all -> 0x0027 }
            closeInputStream(r1)
            return r3
        L_0x0027:
            r3 = move-exception
            goto L_0x0035
        L_0x0029:
            r3 = r1
            goto L_0x002f
        L_0x002b:
            r0 = move-exception
            r1 = r3
            r3 = r0
            goto L_0x0035
        L_0x002f:
            com.liuguang.framework.utils.ImageUtil$Size r0 = ZERO_SIZE     // Catch:{ all -> 0x002b }
            closeInputStream(r3)
            return r0
        L_0x0035:
            closeInputStream(r1)
            throw r3
        L_0x0039:
            com.liuguang.framework.utils.ImageUtil$Size r3 = ZERO_SIZE
            return r3
        */
        throw new UnsupportedOperationException("Method not decompiled: com.liuguang.framework.utils.ImageUtil.getBitMapSize(java.lang.String):com.liuguang.framework.utils.ImageUtil$Size");
    }

    private static Bitmap useBitmap(String str, int i, int i2) {
        Bitmap bitmap;
        String createKey = createKey(str, i, i2);
        synchronized (LOCKED) {
            bitmap = (Bitmap) IMG_CACHE_INDEX.get(createKey);
            if (bitmap != null && CACHE_ENTRIES.remove(createKey)) {
                CACHE_ENTRIES.addFirst(createKey);
            }
        }
        return bitmap;
    }

    private static void destoryLast() {
        synchronized (LOCKED) {
            String str = (String) CACHE_ENTRIES.removeLast();
            if (str.length() > 0) {
                Bitmap bitmap = (Bitmap) IMG_CACHE_INDEX.remove(str);
                if (bitmap != null && !bitmap.isRecycled()) {
                    bitmap.recycle();
                }
            }
        }
    }

    /* access modifiers changed from: private */
    public static String createKey(String str, int i, int i2) {
        if (str == null || str.length() == 0) {
            return "";
        }
        StringBuilder sb = new StringBuilder();
        sb.append(str);
        sb.append("_");
        sb.append(i);
        sb.append("_");
        sb.append(i2);
        return sb.toString();
    }

    /* access modifiers changed from: private */
    public static Bitmap createBitmap(String str, int i, int i2) {
        InputStream inputStream = null;
        Bitmap decodeStream;
        File file = new File(str);
        if (file.exists()) {
                try {
                    inputStream = new FileInputStream(file);
                    Size bitMapSize = getBitMapSize(str);
                    if (bitMapSize.equals(ZERO_SIZE)) {
                        closeInputStream(inputStream);
                        return null;
                    }
                    int max = Math.max(bitMapSize.getWidth() / i, bitMapSize.getHeight() / i2);
                    synchronized (OPTIONS_DECODE) {
                        OPTIONS_DECODE.inSampleSize = max;
                        decodeStream = BitmapFactory.decodeStream(inputStream, null, OPTIONS_DECODE);
                    }
                    closeInputStream(inputStream);
                    return decodeStream;
                } catch (FileNotFoundException e) {
                    e = e;
                    closeInputStream(inputStream);
                }
        }
        return null;
    }

    private static Bitmap createBitmap2(String str, int i, int i2) {
        InputStream inputStream;
        Bitmap decodeStream;
        File file = new File(str);
        if (file.exists()) {
                try {
                    inputStream = new FileInputStream(file);
                    Size bitMapSize = getBitMapSize(str);
                    if (bitMapSize.equals(ZERO_SIZE)) {
                        closeInputStream(inputStream);
                        return null;
                    }
                    int min = Math.min(bitMapSize.getWidth() / i, bitMapSize.getHeight() / i2);
                    synchronized (OPTIONS_DECODE) {
                        OPTIONS_DECODE.inSampleSize = min;
                        decodeStream = BitmapFactory.decodeStream(inputStream, null, OPTIONS_DECODE);
                    }
                    closeInputStream(inputStream);
                    return decodeStream;
                } catch (FileNotFoundException e) {
                    e = e;
                }
        }
        return null;
    }

    private static void closeInputStream(InputStream inputStream) {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                String str = TAG;
                StringBuilder sb = new StringBuilder();
                sb.append("closeInputStream==");
                sb.append(e.toString());
                Log.v(str, sb.toString());
            }
        }
    }

    private static Bitmap compressImage(Bitmap bitmap) {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        int i = 100;
        bitmap.compress(CompressFormat.JPEG, 100, byteArrayOutputStream);
        while (byteArrayOutputStream.toByteArray().length / 1024 > 300) {
            byteArrayOutputStream.reset();
            bitmap.compress(CompressFormat.JPEG, i, byteArrayOutputStream);
            i -= 10;
        }
        bitmap.recycle();
        return BitmapFactory.decodeStream(new ByteArrayInputStream(byteArrayOutputStream.toByteArray()), null, null);
    }

    private static Bitmap getimage(String str) {
        Options options = new Options();
        int i = 1;
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(str, options);
        options.inJustDecodeBounds = false;
        int i2 = options.outWidth;
        int i3 = options.outHeight;
        int i4 = (i2 <= i3 || ((float) i2) <= 600.0f) ? (i2 >= i3 || ((float) i3) <= 600.0f) ? 1 : (int) (((float) options.outHeight) / 600.0f) : (int) (((float) options.outWidth) / 600.0f);
        if (i4 > 0) {
            i = i4;
        }
        options.inSampleSize = i;
        return compressImage(BitmapFactory.decodeFile(str, options));
    }

    public Bitmap convertRotateBitmap(String str) {
        return rotaingImageView(readPictureDegree(str), BitmapFactory.decodeFile(str, new Options()));
    }

    public static int readPictureDegree(String str) {
        try {
            int attributeInt = new ExifInterface(str).getAttributeInt("Orientation", 1);
            if (attributeInt == 3) {
                return 180;
            }
            if (attributeInt == 6) {
                return 90;
            }
            if (attributeInt != 8) {
                return 0;
            }
            return 270;
        } catch (IOException e) {
            e.printStackTrace();
            return 0;
        }
    }

    public static Bitmap rotaingImageView(int i, Bitmap bitmap) {
        Matrix matrix = new Matrix();
        matrix.postRotate((float) i);
        return Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
    }

    public static Bitmap centerSquareScaleBitmap(String str, int i, int i2, int i3) {
        Bitmap bitmap = getBitmap(str, i, i2);
        if (bitmap == null || i3 <= 0) {
            return null;
        }
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        if (width > i3 && height > i3) {
            int max = (Math.max(width, height) * i3) / Math.min(width, height);
            int i4 = width > height ? max : i3;
            if (width > height) {
                max = i3;
            }
            try {
                Bitmap createScaledBitmap = Bitmap.createScaledBitmap(bitmap, i4, max, true);
                try {
                    Bitmap createBitmap = Bitmap.createBitmap(createScaledBitmap, (i4 - i3) / 2, (max - i3) / 2, i3, i3);
                    if (!(createScaledBitmap == null || createScaledBitmap == bitmap || createScaledBitmap == createBitmap)) {
                        createScaledBitmap.recycle();
                        Log.i(TAG, "回收了");
                    }
                    bitmap = createBitmap;
                } catch (Exception e) {
                    e.printStackTrace();
                    return null;
                }
            } catch (Exception e2) {
                e2.printStackTrace();
                return null;
            }
        }
        return bitmap;
    }

    public static Bitmap centerSquareScaleBitmap(String str, int i) {
        Bitmap bitmap;
        Exception e;
        Bitmap bitmap2 = getBitmap(str, i, i);
        if (bitmap2 == null || i <= 0) {
            return null;
        }
        try {
            bitmap = Bitmap.createBitmap(bitmap2, (bitmap2.getWidth() - i) / 2, (bitmap2.getHeight() - i) / 2, i, i);
            if (!(bitmap2 == null || bitmap2 == bitmap)) {
                try {
                    bitmap2.recycle();
                } catch (Exception e2) {
                    e = e2;
                }
            }
        } catch (Exception e3) {
            Exception exc = e3;
            bitmap = bitmap2;
            e = exc;
            e.printStackTrace();
            return bitmap;
        }
        return bitmap;
    }

    public String getBitmapAngle(String str) {
        try {
            return new ExifInterface(str).getAttribute("Model");
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static byte[] bmpToByteArray(Bitmap bitmap, boolean z) {
        Bitmap createScaledBitmap = Bitmap.createScaledBitmap(bitmap, 100, 100, true);
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        createScaledBitmap.compress(CompressFormat.PNG, 100, byteArrayOutputStream);
        if (z && !bitmap.equals(createScaledBitmap)) {
            createScaledBitmap.recycle();
            bitmap.recycle();
        }
        byte[] byteArray = byteArrayOutputStream.toByteArray();
        try {
            byteArrayOutputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return byteArray;
    }

    public static void drawableToFile(Drawable drawable, String str) {
        drawableToFile(drawable, new File(str));
    }

    /* JADX WARNING: Removed duplicated region for block: B:25:0x003e A[SYNTHETIC, Splitter:B:25:0x003e] */
    /* JADX WARNING: Removed duplicated region for block: B:30:0x004b A[SYNTHETIC, Splitter:B:30:0x004b] */
    /* JADX WARNING: Removed duplicated region for block: B:36:0x0056 A[SYNTHETIC, Splitter:B:36:0x0056] */
    /* JADX WARNING: Removed duplicated region for block: B:41:0x0063 A[SYNTHETIC, Splitter:B:41:0x0063] */
    /* Code decompiled incorrectly, please refer to instructions dump. */
    public static void drawableToFile(android.graphics.drawable.Drawable r2, java.io.File r3) {
    }

    public static Bitmap drawableToBitmap(Drawable drawable) {
        @SuppressLint("WrongConstant") Bitmap createBitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(),
                drawable.getOpacity() != -1 ? Config.ARGB_8888 : Config.RGB_565);
        Canvas canvas = new Canvas(createBitmap);
        drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
        drawable.draw(canvas);
        return createBitmap;
    }

    public static String getFilePathFromUri(Context context, Uri uri) {
        Cursor query = context.getContentResolver().query(uri, null, null, null,
                null);
        if (query == null) {
            return uri.getPath();
        }
        query.moveToFirst();
        return query.getString(query.getColumnIndex("_data"));
    }

    public static CompressFormat getImageTypeByFilePath(String str) {
        byte[] bArr = new byte[4];
        try {
            FileInputStream fileInputStream = new FileInputStream(str);
            fileInputStream.read(bArr, 0, bArr.length);
            fileInputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        String upperCase = bytesToHexString(bArr).toUpperCase();
        if (upperCase.contains("FFD8FF")) {
            return CompressFormat.JPEG;
        }
        if (upperCase.contains("89504E47")) {
            return CompressFormat.PNG;
        }
        return CompressFormat.JPEG;
    }

    public static String bytesToHexString(byte[] bArr) {
        StringBuilder sb = new StringBuilder();
        if (bArr == null || bArr.length <= 0) {
            return null;
        }
        for (byte b : bArr) {
            String hexString = Integer.toHexString(b & 255);
            if (hexString.length() < 2) {
                sb.append(0);
            }
            sb.append(hexString);
        }
        return sb.toString();
    }

    public static BitmapDrawable openBigDrawable(Context context, int i) {
        try {
            Options options = new Options();
            options.inPreferredConfig = Config.RGB_565;
            options.inPurgeable = true;
            options.inInputShareable = true;
            InputStream openRawResource = context.getResources().openRawResource(i);
            Bitmap decodeStream = BitmapFactory.decodeStream(openRawResource, null, options);
            openRawResource.close();
            return new BitmapDrawable(context.getResources(), decodeStream);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static File getLocalCover(Context context, String str) {
        File externalStorageDirectory = Environment.getExternalStorageDirectory();
        StringBuilder sb = new StringBuilder();
        sb.append(str);
        sb.append(".jpg");
        File file = new File(externalStorageDirectory, sb.toString());
        if (!file.exists()) {
            AssetCopyer assetCopyer = new AssetCopyer(context);
            try {
                StringBuilder sb2 = new StringBuilder();
                sb2.append("images/");
                sb2.append(file.getName());
                assetCopyer.copyFile(sb2.toString(), file.getParentFile());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return file;
    }

    public static Bitmap toRoundBitmap(Bitmap bitmap) {
        float f;
        float f2;
        float f3;
        float f4;
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        if (width <= height) {
            f4 = (float) (width / 2);
            f3 = (float) width;
            f = f3;
            f2 = 0.0f;
        } else {
            f2 = (float) ((width - height) / 2);
            f = (float) height;
            f3 = ((float) width) - f2;
            width = height;
            f4 = (float) (height / 2);
        }
        Bitmap createBitmap = Bitmap.createBitmap(width, width, Config.ARGB_8888);
        Canvas canvas = new Canvas(createBitmap);
        Paint paint = new Paint();
        Rect rect = new Rect((int) f2, (int) 0.0f, (int) f3, (int) f);
        Rect rect2 = new Rect((int) 0.0f, (int) 0.0f, (int) f, (int) f);
        RectF rectF = new RectF(rect2);
        paint.setAntiAlias(true);
        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(-12434878);
        canvas.drawRoundRect(rectF, f4, f4, paint);
        paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
        canvas.drawBitmap(bitmap, rect, rect2, paint);
        return createBitmap;
    }
}
